package com.qf.realm;

import com.qf.pojo.SysUsers;
import com.qf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String username = (String) principals.getPrimaryPrincipal();

        SysUsers user = userService.findByUsername(username);

        //授权(用户的角色和权限信息)
        SimpleAuthorizationInfo  authorizationInfo = new SimpleAuthorizationInfo();



        Set<String> roles = userService.queryRolesByUserId(user.getId());
        Set<String> perms = userService.queryPermsByUserId(user.getId());

//        设置角色 Set集合<String>
        authorizationInfo.setRoles(roles);
//        设置权限集合 Set<String>
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的认证信息(用户名，密码，用户的其他信息)
        //获取用户输入的账号和密码
        String username = (String) token.getPrincipal();
        String password = new String((char[])token.getCredentials());
        System.out.println("用户输入的密码：" + password);

        //根据用户名从数据库查询用户信息
        SysUsers user = userService.findByUsername(username);
        System.out.println("数据库的密码：" + user.getPassword());
        if(user == null ){
            throw  new UnknownAccountException("未知的用户名");
        }

        if(user.getPassword() == null || !user.getPassword().equals(password)){
            throw new CredentialsException("密码错误");
        }

        if(user.getStatus() != 1){
            throw new LockedAccountException("账号已锁定");
        }

        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username ,password, user.getRealname());


        return authenticationInfo;
    }
}
